package com.beyond.trace.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beyond.trace.domain.TraceBase;
import com.beyond.trace.domain.TraceProduct;
import com.beyond.trace.domain.TraceScanStatistics;
import com.beyond.trace.mapper.TraceBaseMapper;
import com.beyond.trace.mapper.TraceProductMapper;
import com.beyond.trace.mapper.TraceScanStatisticsMapper;
import com.beyond.trace.service.ITraceBaseService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.SnowUtil;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 基地信息Service业务层处理
 * 
 * @author yao
 * @date 2022-03-02
 */
@Service
public class TraceBaseServiceImpl extends ServiceImpl<TraceBaseMapper, TraceBase> implements ITraceBaseService
{
    @Resource
    private TraceBaseMapper traceBaseMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private TraceScanStatisticsMapper scanStatisticsMapper;

    @Resource
    private TraceProductMapper traceProductMapper;
    /**
     * 查询基地信息
     * 
     * @param baseId 基地信息ID
     * @return 基地信息
     */
    @Override
    public TraceBase selectTraceBaseById(Long baseId)
    {
        QueryWrapper<TraceBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("base_id",baseId);
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            queryWrapper.eq("depart_id",SecurityUtils.getUserDepartId());
        }
        return traceBaseMapper.selectOne(queryWrapper);
    }

    /**
     * 查询基地信息列表
     * 
     * @param traceBase 基地信息
     * @return 基地信息
     */
    @Override
    public List<TraceBase> selectTraceBaseList(TraceBase traceBase)
    {
        QueryWrapper<TraceBase> queryWrapper = new QueryWrapper<>();
//        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
//            queryWrapper.eq("depart_id",SecurityUtils.getUserDepartId());
//        }
        if(StringUtils.isNotEmpty(traceBase.getBaseAddress())) {
            queryWrapper.like("base_address",traceBase.getBaseAddress());
        }
        if(StringUtils.isNotEmpty(traceBase.getBaseName())) {
            queryWrapper.eq("base_name",traceBase.getBaseName());
        }
        if(StringUtils.isNotEmpty(traceBase.getBasePerson())) {
            queryWrapper.eq("base_person",traceBase.getBasePerson());
        }
        return traceBaseMapper.selectList(queryWrapper);
    }

    /**
     * 新增基地信息
     * 
     * @param traceBase 基地信息
     * @return 结果
     */
    @Override
    public Integer insertTraceBase(TraceBase traceBase)
    {
        traceBase.setCreateTime(DateUtils.getNowDate());
        traceBase.setUpdateTime(DateUtils.getNowDate());
        traceBase.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        traceBase.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        traceBase.setDepartId(String.valueOf(SecurityUtils.getUserDepartId()));
        if(StringUtils.isEmpty(traceBase.getBaseNo())) {
            traceBase.setBaseNo(SnowUtil.getId());
        }
        int i = baseMapper.insert(traceBase);
        if (i < 1) {
            throw new RuntimeException("出错啦");
        }
        return i;
    }

    /**
     * 修改基地信息
     * 
     * @param traceBase 基地信息
     * @return 结果
     */
    @Override
    public int updateTraceBase(TraceBase traceBase)
    {
        traceBase.setUpdateTime(DateUtils.getNowDate());
        traceBase.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        int i = baseMapper.updateById(traceBase);
        if (i < 1) {
            throw new RuntimeException("出错啦");
        }
        return i;
    }

    /**
     * 批量删除基地信息
     * 
     * @param baseIds 需要删除的基地信息ID
     * @return 结果
     */
    @Override
    public int deleteTraceBaseByIds(Long[] baseIds)
    {
        QueryWrapper<TraceBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("base_id",Arrays.asList(baseIds));
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            queryWrapper.eq("depart_id",SecurityUtils.getUserDepartId());
        }
        return traceBaseMapper.delete(queryWrapper);
    }

    /**
     * 删除基地信息信息
     * 
     * @param baseId 基地信息ID
     * @return 结果
     */
    @Override
    public int deleteTraceBaseById(Long baseId)
    {
        QueryWrapper<TraceBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("base_id",Arrays.asList(baseId));
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            queryWrapper.eq("depart_id",SecurityUtils.getUserDepartId());
        }
        return traceBaseMapper.delete(queryWrapper);
    }


    /**
     * 查询基地信息
     *
     * @param productId 产品Id
     * @return 基地信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public TraceBase selectTraceBaseByProductId(Long productId, HttpServletRequest request) {
        try {
            TraceBase traceBase = traceBaseMapper.selectTraceBaseByProductId(productId);
            SysUser sysUser = new SysUser();
            sysUser.setDeptId(Long.valueOf(traceBase.getDepartId()));
            List<SysUser> sysUsers = sysUserMapper.selectUserList(sysUser);
            if(!sysUsers.isEmpty()) {
                String userName = sysUsers.get(0).getUserName();

                Map<String,String> params = new HashMap<>();
                params.put("username",userName);
                params.put("password","123456");
                params.put("issuer","enroll");
                params.put("style","1");

                try {
                    String result = HttpUtil.post("http://yun.bigdata5s.com/api/user/passport/login", JSON.toJSONString(params));
                    log.debug("请求返回的结果："+result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    if("200".equals(jsonObject.getString("status"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        traceBase.setToken(data.getString("token"));
                        traceBase.setUserId(data.getString("userid"));

                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return traceBase;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String CityName(String name) {
        String province = "";
        if (name.contains("省")) {
            province = name.replace("省", "");
            return province;
        }
        if (name.contains("自治区")) {
            province = name.replace("自治区", "");
            if (province.contains("壮族") || province.contains("回族") || province.contains("维吾尔")) {
                province = province.replace("壮族","");
            }
            if (province.contains("回族")) {
                province = province.replace("回族","");
            }
            if (province.contains("维吾尔")) {
                province = province.replace("维吾尔","");
            }
            return province;
        }
        if (name.contains("特别行政区")) {
            province = name.replace("特别行政区", "");
            return province;
        }
        if (name.contains("市")) {
            province = name.replace("市", "");
            return province;
        }
        return province;
    }

    /**
     * @descrotion 添加扫描次数
     * @auther yaojianbo
     * @param productId 产品Id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addScanCount(Long productId, HttpServletRequest request) {
        try {
            String realAddressByIP = AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(request));
            TraceProduct traceProduct = traceProductMapper.selectById(productId);
            if(StringUtils.isNull(traceProduct)) {
                throw new Exception("没有查到产品信息");
            }
            String[] split = realAddressByIP.split(" ");
            TraceScanStatistics scanStatistics = new TraceScanStatistics();
            String cityName = "";
            if (split[0].equals("内网IP")) {
                cityName = "四川";
            } else {
                cityName = CityName(split[0]);
            }
            scanStatistics.setProvince(cityName);
            scanStatistics.setProduct(traceProduct.getProductName());
            scanStatistics.setStatus(1);
            scanStatistics.setCreateTime(new Date());
            scanStatisticsMapper.insert(scanStatistics);
            Integer newCount = StringUtils.isNull(traceProduct.getCount()) ? 1 : traceProduct.getCount() + 1;
            TraceProduct trace = new TraceProduct();
            trace.setProductId(traceProduct.getProductId());
            trace.setCount(newCount);
            traceProductMapper.updateById(trace);
        } catch (Exception e) {
            TraceScanStatistics scanStatistics = new TraceScanStatistics();
            scanStatistics.setStatus(0);
            scanStatistics.setCreateTime(new Date());
            scanStatisticsMapper.insert(scanStatistics);
            e.printStackTrace();
        }
        return 1;
    }

}
